// pages/index/colleague.js

const app = getApp();

import {
  homelist,
  scopebusiness,
  circleDetail,
  circleactivity,
  indexTabMyself,
  getCompanyByUser,
  collect,
  delCollect
} from '../../utils/http';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    v: app.globalData.v, //版本
    lang: app.vSwitch(), //版本
    wxApp: app.config.wxApp,
    theme: app.cSwitch(true), //主题色
    isIphoneX: app.globalData.isIphoneX,
    showdetail: false,
    // 页面垂直滑动的距离
    scrollTop: undefined,

    detail: null,

    // selectShow: false,
    // mainActiveIndex: 0,
    activeId: null,
    // items: [],


    popUpshow: false, //完善信息弹窗
    popUpshow2: false, //晚上公司信息
    popUpInfo: {
      img: '/pages/images/pop/1.png',
      tit: '请完善您的个人信息',
      dec: '欢迎您使用' + app.config.wxApp.wxName + '小程序!初次登录请您完善您的个人信息',
      url: '/pages/mine/info/index'
    },

    popUpInfo2: {
      img: '/pages/images/pop/1.png',
      tit: '请添加您的' + app.vSwitch().a4,
      dec: '您可以在我的页面中，添加您的' + app.vSwitch().a4,
      url: '/pages/mine/company/index'
    },
    // popUpInfo: {
    //   img: '/pages/images/pop/2.png',
    //   tit: '收藏成功',
    //   dec: '您可以在名片夹中查看您收藏的名片',
    // }

    // 分页
    page: 1,
    size: 10,
    pages: 0,
    current: 0,
    noData: false,
    list: [],
    keyWord: '',
    manageRange: '',

    tabTit: [],
    // tabTitAll: [],
    activeKey: 0,

    dqname:"",//当前用户名字
    qiehuan_style:2,//1列表2专栏
  },

  async init() {
    let t = this;
    this.setData({
      page: 1,
      noData: false,
      pages: 0,
      current: 0,
    })
    // await t.circleDetail();
    // await t.circleactivity(); //活动资讯
    await t.getMore();
    await t.indexTabMyself();
    // await t.scopebusiness();
  },

  // circleactivity() {
  //   let t = this;
  //   var promise = new Promise((resolve, reject) => {
  //     if (t.data.pages >= t.data.current) {
  //       circleactivity({
  //         page: 1,
  //         pageSize: 3,
  //         type: ''
  //       }).then(r => {
  //         if (r.httpCode == 200 || r.code == 0) {
  //           if (r.data.records.length) {

  //             r.data.records.forEach(i => {
  //               i.ksTime = i.activityStartTime.split(' ');
  //               i.ksTime[1] = i.ksTime[1].substring(0, i.ksTime[1].length - 3)
  //             })
  //             t.setData({
  //               activityArr: r.data.records
  //             })
  //           }

  //         }

  //         resolve();
  //       })
  //     } else {
  //       t.setData({
  //         noData: true
  //       })
  //       resolve();
  //     }
  //   });
  //   return promise;
  // },

  indexTabMyself() {
    let t = this;
    return new Promise((resolve, reject) => {
      indexTabMyself({
        type: t.data.v ? 1 : 2
      }).then(r => {
        if (r.code == 0 && r.data.length) {
          this.setData({
            tabTit: null
          })
          t.setData({
            tabTit: r.data
          })
          wx.setStorageSync('devIndexLabel', r.data)
          wx.lin.flushSticky()
        } else {
          t.scopebusiness()
        }
        resolve();
      })

    })

  },

  circleDetail() {
    let t = this;
    var promise = new Promise((resolve, reject) => {
      circleDetail().then(r => {
        if (r.code == 0) {
          this.setData({
            detail: r.data
          })
        }
        resolve();
      })
    });
  },

  getMore() {
    let t = this;
    var promise = new Promise((resolve, reject) => {
      if (t.data.pages >= t.data.current) {
        homelist({
          page: t.data.page,
          pageSize: t.data.size,
          // keyWord: t.data.keyWord,
          manageRange: t.data.activeId ? t.data.activeId : ''
        }).then(r => {
          if (r.httpCode == 200 || r.code == 0) {
            let d;
            if (t.data.page == 1) {
              d = [];
            } else {
              d = t.data.d;
            }
            if (r.data.records.length) {
              r.data.records.forEach(i => {
                i.manageRangeName = i.manageRangeName ? i.manageRangeName.split(',') : '';
                i.imagedots = 0
                d.push(i)
              })
              if (r.data.records.length < r.data.size) {
                t.setData({
                  noData: true,
                })
              } else {
                t.setData({
                  noData: false,
                })
              }
            } else {
              t.setData({
                noData: true,
              })
            }
            t.setData({
              d,
              page: ++t.data.page,
              pages: r.data.pages,
              current: r.data.current
            })
            wx.lin.flushSticky()
          }

          resolve();
        })
      } else {
        t.setData({
          noData: true
        })
        resolve();
      }
    });
    return promise;
  },
  scopebusiness() {
    let t = this;
    return new Promise((resolve, reject) => {
      scopebusiness({
        type: t.data.v ? 1 : 2
      }).then(r => {
        if (r.code == 0) {
          if (r.data.length) {
            let tabTitAll = []
            r.data.forEach((i, index) => {
              if (tabTitAll.length < 3) {
                tabTitAll.push(i)
              }
            })
            t.setData({
              // items: r.data,
              tabTit: tabTitAll
            })
            wx.lin.flushSticky()
          }
        }
        resolve();
      })
    })
  },




  // 跳转小程序
  // tiaozhuanxiaochengxu(){
  //   wx.navigateToMiniProgram({
  //     appId: 'wxcfe5bb971d917e9b',
  //     path: 'pages/index/index',
  //     extraData: {
  //       foo: 'bar'
  //     },
  //     envVersion: 'release',
  //     success(res) {
  //       // 打开成功
  //     }
  //   })
  // },

  // onClickNav({
  //   detail = {}
  // }) {
  //   this.setData({
  //     mainActiveIndex: detail.index || 0,
  //   });
  // },

  // onClickItem({
  //   detail = {}
  // }) {
  //   const activeId = this.data.activeId === detail.id ? null : detail.id;
  //   console.log(detail)
  //   this.setData({
  //     tabTit: null
  //   })
  //   this.setData({
  //     activeId,
  //     // selectShow: false,
  //     page: 1,
  //     pages: 0,
  //     current: 0,
  //     noData: false,
  //     tabTit: [{
  //       name: detail.text,
  //       id: detail.id
  //     }],
  //   })

  //   this.getMore();
  //   this.setData({
  //     activeKey: '1'
  //   })
  // },

  // onClose() {
  //   this.setData({
  //     selectShow: false
  //   })
  // },
  // open() {
  //   this.setData({
  //     selectShow: true
  //   })
  // },

  changeTabs({
    detail = {}
  }) {
    console.log(detail)
    this.setData({
      activeId: detail.currentIndex ? this.data.tabTit[detail.currentIndex - 1].id : '',
      page: 1,
      noData: false,
      pages: 0,
      current: 0,
    })
    this.getMore();
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: app.config.wxApp.wxName,
    })
    if (app.globalData.token && !app.globalData.patterns) {
      app.userInfo(true).then(r => {
        this.setData({
          popUpshow: r.headPic && r.organizationalId ? false : true
        })
        if (r) {
          this.setData({
            pageFlag: true
          })
        }
        if (r.headPic && r.organizationalId && r.organizationalIsDetail != 2) {
          getCompanyByUser().then(r => {
            if (r.code == 0 && r.data) {
              if (!r.data || !r.data.length) {
                this.setData({
                  popUpshow2: true
                })
              } else {
                this.setData({
                  popUpshow2: false
                })
              }
            }
          })
          // if (!r.circleCompanyList || !r.circleCompanyList.length) {
          //   this.setData({
          //     popUpshow2: true
          //   })
          // } else {
          //   this.setData({
          //     popUpshow2: false
          //   })
          // }
        }
        if (!this.data.d || !this.data.d.length) {
          this.init();
        }
      });
    } else {
      if (app.globalData.patterns) {
        wx.switchTab({
          url: this.data.v ? '/pages/share/index' : '/pages/activity/index',
        })
      } else {
        wx.reLaunch({
          url: '/pages/login/index',
        })
      }
    }

    app.userInfo().then(r => {
      this.setData({
        dqname: r.name
      })
    });
  },

  // onPageScroll(res) {
  //   wx.lin.setScrollTop(res.scrollTop)
  // },

  lookmore: function () {
    this.setData({
      showdetail: true
    })
  },
  closedetail: function () {
    this.setData({
      showdetail: false
    })
  },

  // bindMultiPickerChange: function (e) {
  //   console.log('picker发送选择改变，携带值为', e.detail.value)

  //   this.setData({
  //     multiIndex: e.detail.value
  //   })
  // },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);

  },

  goPage(e) {
    app.goPage(e.mark);
  },

  bindchange:function(e)
  {
    console.log(e)
    var index = e.detail.current
    if(index == this.data.d.length-1)
    {
      if (!this.data.noData) {
        this.getMore();
      }
    }
  },

  imgbindchange:function(e)
  {
    console.log(e)
    var index1 = e.detail.current
    var itemindex = e.target.dataset.index
    var dd = this.data.d
    dd.forEach((i, index) => {
      if(index == itemindex)
      {
        i.imagedots = index1
      }
    })
    this.setData({
      d:dd
    })
    console.log(this.data.d)

  },

  showbigimg:function(e)
  {
    var urls = e.currentTarget.dataset.urls
    var arr = []
    var current = e.currentTarget.dataset.currurl
    urls.forEach((i, index) => {
      arr.push(i.url)
    })

    wx.previewImage({
      urls: arr,
      current:current
    })
  },


    // 添加到通讯录
    addPhoneContact(e) {
      var item = e.currentTarget.dataset.item
      let t = this;
      let str = [];
      item.circleCompanyList.forEach(i => {
        str.push(i.name)
      })
      wx.addPhoneContact({
        firstName: item.name, //姓名
        mobilePhoneNumber: item.phone, //电话
        email: item.mail, //邮箱
        organization: str.toString(), //公司
        remark: item.manageRangeName, //备注
      })
    },


      // 收藏按钮
  collect(e) {
    var index = e.currentTarget.dataset.index
    var item = this.data.d[index]
    let t = this;
    if (item.isCollection == 1) {
      delCollect({
        uid: item.id
      }).then(r => {
        if (r.code == 0) {
          wx.showToast({
            title: '取消成功',
            mask: true,
          })
          item.isCollection=2
          t.setData({
            d:t.data.d
          })
        } else {
          wx.showToast({
            title: '取消失败',
            mask: true,
            icon: 'none'
          })
        }
      })
    } else {
      collect({
        uid: item.id
      }).then(r => {
        if (r.code == 0) {
          wx.showToast({
            title: '关注成功',
            mask: true,
          })
          item.isCollection=1
          t.setData({
            d:t.data.d
          })
        } else {
          wx.showToast({
            title: '关注失败',
            mask: true,
            icon: 'none'
          })
        }
      })
    }
  },

  qiehuan:function()
  {
    this.setData({
      qiehuan_style:this.data.qiehuan_style==1?2:1
    })
  },


ok:function()
{

},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {



  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  comeHere(e) {
    app.location(e.mark)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    this.init();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.noData) {
      this.getMore();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    
    if(e.target)
    {
      let name;
      let wxApp = app.config.wxApp;
      name = this.data.dqname + '分享给您' + e.target.dataset.item.name + '的名片';
      return app.share({
        name,
        url: '/pages/index/detail?id=' + e.target.dataset.item.id,
        img: wxApp.mpShare
      });
    }
    

    return app.share();
  }
})